package java8.xml.sax;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import java.util.ArrayList;
import java.util.List;

/**
 * @author 周宇
 * @create 2020-08-28 16:15
 */
public class BookHander extends DefaultHandler {

    private Book book;
    private List<Book> list;
    private String currenTag;

    public void setList(List<Book> list) {
        this.list = list;
    }

    public List<Book> getList() {
        return list;
    }

    //当加载xml文档的时候触发
    @Override
    public void startDocument() throws SAXException {
        super.startDocument();
        System.out.println("====== 开始加载XML文件 ======");
        //当加载xml的时候，创建一个存储对象的容器
        list = new ArrayList<>();
    }

    //当遇到元素的时候触发
    @Override
    public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
        super.startElement(uri, localName, qName, attributes);
        currenTag = qName;//把当前的标签名复制给currenTag
        if (qName.equals("book")) {
            book = new Book();
            if (attributes != null) {
                String id = attributes.getValue("id");
                if (id != null) {
                    //吧得到的id值封装到book对象的id属性中
                    book.setId(Integer.parseInt(id));
                }
            }
        }
    }

    //读取文本消息的时候触发
    @Override
    public void characters(char[] ch, int start, int length) throws SAXException {
        super.characters(ch, start, length);
        if (currenTag.equals("title")) {
            book.setTitle(new String(ch, start, length));
        } else if (currenTag.equals("author")) {
            book.setAuthor(new String(ch, start, length));
        } else if (currenTag.equals("price")) {
            book.setPrice(Double.parseDouble(new String(ch, start, length)));
        }
    }

    //当读取完一个元素的时候触发
    @Override
    public void endElement(String uri, String localName, String qName) throws SAXException {
        super.endElement(uri, localName, qName);
        currenTag = ""; //把currenTag里面的值清空
        if(qName.equals("book")){
            list.add(book);
        }
    }

    //当document文档解析结束时触发
    @Override
    public void endDocument() throws SAXException {
        super.endDocument();
        System.out.println("------ 文档开始解析结束 ------");

    }
}
